package org.itboys.mobile.service.mongo.mobile;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.KitchenCountDto;
import org.itboys.mobile.dto.count.KitchenCountProductDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.entity.mongo.PearlCart;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mysql.mobile.product.SundayMobileProductService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/10/18.
 * @author 朱坤涛
 */
@Service
public class PearlMobileCartService extends BaseMongoService<PearlCart>{
    @Autowired
    private SundayMobileProductService productService;
    @Autowired
    private SundayMobileMemberService memberService;
    @Resource(name = "mobileDs")
    private MongoDataSource pearlDataSource;
    @Override
    protected MongoDataSource getMongoDataSource(){ return pearlDataSource;}
    @Override
    protected Class<PearlCart> getEntityClass(){ return PearlCart.class;}

    /**
     * 新增购物车（支持批量新增）。
     * @param memberId
     * @param productIds
     * @param nums
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的
     * @return
     */
    public List<Long> addCart(Long memberId,List<Long> productIds,List<Integer> nums,Integer cartType){
        if (ListUtil.isNull(productIds)||ListUtil.isNull(nums)||(productIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        //如果是立即购买加入购物车，先删除原来购物车中立即购买加入的数据
        if (cartType== SundayCommonConstants.cart_type_buy_now){
            deleteCart(null,memberId,SundayCommonConstants.cart_type_buy_now);
        }
        //返回结果
        List<Long> cartIds = new ArrayList<Long>();
        //获取要加入的商品
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("ids",productIds);
        List<SundayProduct> products = productService.select(param);
        //旧购物车数据
        param.clear();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        param.put("cartType",cartType);
        List<PearlCart> needToAdd =new ArrayList<>();
        //比对出哪一些商品是需要新增的，哪一些是增加数量的
        for(int i=0;i< products.size();i++){
            SundayProduct product = products.get(i);
            Integer num =nums.get(i);
            boolean isExist=false;

            //本次需要新增的商品
            if(!isExist){
                needToAdd.add(new PearlCart(memberId, product.getId(), num,cartType));
            }
        }
        if(ListUtil.isNotNull(needToAdd)){
            super.batchSave(needToAdd);
        }
        for(PearlCart needToAd:needToAdd){
            cartIds.add(needToAd.getId());
        }
        return cartIds;
    }

    /**
     * 修改购物车数量，支持批量修改
     * @param memberId
     * @param cartIds
     * @param nums
     */
    public void updateCart(Long memberId,List<Long> cartIds,List<Integer> nums){
        if (ListUtil.isNull(cartIds)||ListUtil.isNull(nums)||(cartIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("id in",cartIds);
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        List<PearlCart> carts = super.list(param);
        for(int i=0;i<carts.size();i++){
            PearlCart cart = carts.get(i);
            Integer num = nums.get(i);
            //数量变更后才操作数据库。执行修改
            if(cart.getNum()!=num){
                super.update(cart.getId(),"num",num);
            }
        }
    }

    /**
     * 删除购物车，支持批量删除
     * @param cartIds
     * @param memberId
     * @param cartType
     */
    public void deleteCart(List<Long> cartIds ,Long memberId,Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        if(cartType!=null){
            param.put("cartType",cartType);
        }

        super.delete(param);
    }
    /**
     * 获取购物车，不分页，返回上
     */

    public KitchenCountDto getCart(Long memberId, List<Long> cartIds, Integer cartType) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        param.put("isDeleted", 0);
        if (ListUtil.isNotNull(cartIds)) {
            param.put("id in", cartIds);
        }
        if (cartType != null) {
            param.put("cartType", cartType);
        }
        List<PearlCart> carts = super.list(param);
        KitchenCountDto countDto = new KitchenCountDto();
        countDto.setTotalAmount(new BigDecimal("0"));
        countDto.setPayAmount(new BigDecimal("0"));
        countDto.setMemberId(memberId);
        if (ListUtil.isNull(carts)) return countDto;
        //对应的商品数据
        List<Long> productIds = new ArrayList<Long>();
        for (PearlCart cart : carts) {
            productIds.add(cart.getProductId());
        }
        param.clear();
        param.put("ids", productIds);
        List<SundayProduct> products = productService.select(param);
       // List<SundayProductDto> productDtos = productService.packageDtoMuilt(products);
        List<KitchenCountProductDto> countProducts = new ArrayList<KitchenCountProductDto>();
        Double totalAmount = 0.00;
        Double payAmount = 0.00;
        Double costAmount = 0.00;


        countDto.setTotalAmount(new BigDecimal(totalAmount).setScale(2, BigDecimal.ROUND_HALF_UP));
        countDto.setPayAmount(new BigDecimal(payAmount).setScale(2, BigDecimal.ROUND_HALF_UP));
        countDto.setCostAmount(new BigDecimal(costAmount).setScale(2, BigDecimal.ROUND_HALF_UP));

        countDto.setProducts(countProducts);

        return countDto;
    }

}
